<template>
  <el-tabs v-model="activeName" tab-position="left" type="border-card">
    <el-tab-pane label="基础通信 Topic" name="base">

      <avue-crud :option="optionBase"
                 :data="dataBase"
                 v-model:page="pageBase"
                 :table-loading="loading"
                 ref="crudBase"
                 :span-method="spanMethodBase"
                 @on-load="onLoadBase">

      </avue-crud>

    </el-tab-pane>
    <el-tab-pane label="物模型通信 Topic" name="tsl">

      <avue-crud :option="optionTsl"
                 :data="dataTsl"
                 v-model:page="pageTsl"
                 :table-loading="loading"
                 ref="crudTsl"
                 :span-method="spanMethodTsl"
                 @on-load="onLoadTsl">

      </avue-crud>

    </el-tab-pane>
    <el-tab-pane v-if="customTopic" label="自定义 Topic" name="custom">

      <avue-crud :option="option"
                 v-model:search="search"
                 v-model:page="page"
                 v-model="form"
                 :table-loading="loading"
                 :data="data"
                 :permission="permissionList"
                 :before-open="beforeOpen"
                 ref="crud"
                 @row-update="rowUpdate"
                 @row-save="rowSave"
                 @row-del="rowDel"
                 @search-change="searchChange"
                 @search-reset="searchReset"
                 @selection-change="selectionChange"
                 @current-change="currentChange"
                 @size-change="sizeChange"
                 @refresh-change="refreshChange"
                 @on-load="onLoad">
        <template #alert-form="{}">
          <el-alert type="info" :closable="false">
            <el-text size="small">Topic 格式必须以"/"进行分层，区分每个类目。其中相关固定参数名已经规定好。</el-text>
            <el-text size="small">${productKey} 匹配产品标识 ProductKey。</el-text>
            <el-text size="small">${deviceName} 匹配设备模块 DeviceName。</el-text>
          </el-alert>
        </template>
        <template #topicPreview-form="{}">
          <el-text size="small">{{getTopicPrefix()}}{{ this.form.topic }}</el-text>
        </template>
      </avue-crud>

    </el-tab-pane>
  </el-tabs>
</template>

<script>
import {getDetailByKey} from "@/api/iot/product";
import {getList as getTopicList} from "@/api/iot/topic";
import {add, getDetail, getList, remove, update} from "@/api/iot/product/topic";
import {optionBase, optionTsl, optionCustom} from "@/option/iot/productTopic";
import {mapGetters} from "vuex";
import { validatenull } from '@/utils/validate';

export default {
  name: 'productTopic',
  props: {
    productKey: String,
    productId: String,
  },
  data() {
    return {
      activeName: 'base',
      customTopic: true,
      optionBase: optionBase,
      optionTsl: optionTsl,
      dataBase: [],
      dataTsl: [],
      dataCustom: [],
      form: {},
      query: {},
      search: {},
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      pageBase: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      pageTsl: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      option: optionCustom,
      data: [],
      selectionList: [],
      loading: false,
      spanArrBase: [
        {
          prop: 'featureName',
          span: []
        },
        {
          prop: 'accessName',
          span: []
        }
      ],
      spanArrTsl: [
        {
          prop: 'featureName',
          span: []
        },
        {
          prop: 'accessName',
          span: []
        }
      ],
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: true,
        delBtn: true,
        editBtn: true,
        viewBtn: false,
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    },
  },
  created() {
    this.init();
  },
  watch: {
    productId() {
      if (!validatenull(this.productId)) {
        this.init();
        this.onLoad(this.page);
        this.onLoadTsl(this.pageTsl);
        this.onLoadBase(this.pageBase);
      }
    }
  },
  methods: {
    init() {
      getDetailByKey(this.productKey).then(res => {
        this.detail = res.data.data;
      });
    },
    getTopicPrefix() {
      return "/blade/custom/" + this.productKey + "/${deviceName}/";
    },
    rowSave(row, done, loading) {
      row.type = "custom";
      row.productId = this.productId;
      row.topic = this.getTopicPrefix() + row.topic;
      add(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        window.console.log(error);
      });
    },
    rowUpdate(row, index, done, loading) {
      row.type = "custom";
      row.productId = this.productId;
      row.topic = this.getTopicPrefix() + row.topic;
      update(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        console.log(error);
      });
    },
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
    },
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
          this.form.topic = this.form.topic.replace(this.getTopicPrefix(), "");
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;

      const {
        type,
        feature,
        access,
      } = this.query;

      let values = {
        type_equal: type,
        feature_equal: feature,
        access_equal: access,
        type: "custom",
        productId: this.productId
      };

      getList(page.currentPage, page.pageSize, values).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    onLoadBase(page, params = {}) {
      this.loading = true;
      params = {
        ...params,
        type: "base"
      }
      getTopicList(page.currentPage, page.pageSize, params).then(res => {
        const data = res.data.data;
        this.pageBase.total = data.total;
        this.dataBase = data.records.map(item => {
          return {
            ...item,
            topic: item.topic.replace(/\${productKey}/g, this.productKey) // 替换 topic 属性值
          };
        });
        this.rowSortBase()
        this.rowCalcBase();
        this.loading = false;
      });
    },
    onLoadTsl(page, params = {}) {
      this.loading = true;
      params = {
        ...params,
        type: "tsl"
      }
      getTopicList(page.currentPage, page.pageSize, params).then(res => {
        const data = res.data.data;
        this.pageTsl.total = data.total;
        this.dataTsl = data.records.map(item => {
          return {
            ...item,
            topic: item.topic.replace(/\${productKey}/g, this.productKey) // 替换 topic 属性值
          };
        });
        this.rowSortTsl()
        this.rowCalcTsl();
        this.loading = false;
      });
    },
    rowCalcBase() {
      this.spanArrBase.forEach((ele, index) => {
        let parent
        if (index !== 0) parent = this.spanArrBase[ele.parent || index - 1].span
        ele.span = this.rowSpanBase(ele.prop, parent)
      })
    },
    rowSortBase() {
      this.spanArrBase.forEach((ele, index) => {
        let key = ele.prop
        this.dataBase = this.dataBase.sort((a, b) => {
          let flag = true;
          for (let i = 0; i < index; i++) {
            let prop = this.spanArrBase[i].prop
            flag = flag && a[prop] === b[prop]
          }
          if (flag) {
            if (a[key] < b[key]) {
              return 1;
            } else if (a[key] > b[key]) {
              return -1;
            }
            return 0;
          }
          return 0;
        })
      })
    },
    rowSpanBase(key, parent) {
      let list = [];
      let position = 0;
      this.dataBase.forEach((item, index) => {
        if (index === 0) {
          list.push(1)
          let position = 0;
        } else {
          if (this.dataBase[index][key] === this.dataBase[index - 1][key]) {
            if (parent && parent[index] !== 0) {
              list.push(1)
              position = index
            } else {
              list[position] += 1;
              list.push(0)
            }
          } else {
            list.push(1)
            position = index
          }
        }
      })
      return list
    },
    spanMethodBase({row, column, rowIndex, columnIndex}) {
      for (let i = 0; i < this.spanArrBase.length; i++) {
        const ele = this.spanArrBase[i]
        if (column.property === ele.prop) {
          const _row = ele.span[rowIndex];
          const _col = _row > 0 ? 1 : 0;
          return {
            rowspan: _row,
            colspan: _col
          }
        }
      }
    },
    rowCalcTsl() {
      this.spanArrTsl.forEach((ele, index) => {
        let parent
        if (index !== 0) parent = this.spanArrTsl[ele.parent || index - 1].span
        ele.span = this.rowSpanTsl(ele.prop, parent)
      })
    },
    rowSortTsl() {
      this.spanArrTsl.forEach((ele, index) => {
        let key = ele.prop
        this.dataTsl = this.dataTsl.sort((a, b) => {
          let flag = true;
          for (let i = 0; i < index; i++) {
            let prop = this.spanArrTsl[i].prop
            flag = flag && a[prop] === b[prop]
          }
          if (flag) {
            if (a[key] < b[key]) {
              return 1;
            } else if (a[key] > b[key]) {
              return -1;
            }
            return 0;
          }
          return 0;
        })
      })
    },
    rowSpanTsl(key, parent) {
      let list = [];
      let position = 0;
      this.dataTsl.forEach((item, index) => {
        if (index === 0) {
          list.push(1)
          let position = 0;
        } else {
          if (this.dataTsl[index][key] === this.dataTsl[index - 1][key]) {
            if (parent && parent[index] !== 0) {
              list.push(1)
              position = index
            } else {
              list[position] += 1;
              list.push(0)
            }
          } else {
            list.push(1)
            position = index
          }
        }
      })
      return list
    },
    spanMethodTsl({row, column, rowIndex, columnIndex}) {
      for (let i = 0; i < this.spanArrTsl.length; i++) {
        const ele = this.spanArrTsl[i]
        if (column.property === ele.prop) {
          const _row = ele.span[rowIndex];
          const _col = _row > 0 ? 1 : 0;
          return {
            rowspan: _row,
            colspan: _col
          }
        }
      }
    }
  }
};
</script>

<style>
.cursor {
  cursor: pointer;
}
</style>
